#include <QApplication>
#include <QtConcurrentRun>
#include <QThread>

#include <lgpl-components/cobjectmanager.h>

#include "cprofile.h"
#include "cprofilefactory.h"
#include "iprofile.h"

CProfileFactory::CProfileFactory(QObject *parent) :
    QObject(parent)
{
}

QStringList CProfileFactory::networks()
{
    QStringList nw;
    QList<IProfile *> avaibleNetwoks = CObjectManager::instance()->components<IProfile>();

    foreach(IProfile * p, avaibleNetwoks) {
        nw.append(p->networkId());
    }
    return nw;
}

CProfile * CProfileFactory::getProfile(const CAuthInfo &authInfo)
{
    QList<IProfile *> avaibleNetwoks = CObjectManager::instance()->components<IProfile>();

    foreach(IProfile * p, avaibleNetwoks) {
        if (p->networkId() == "vkontakte") { // FIX ME: other protocols
            // avoid interface freeze cause long term initialization
            QFuture<CProfile *> future = QtConcurrent::run(&CProfileFactory::createInstanceRemote, p,
                                                           authInfo, QThread::currentThread());
            while (!future.isFinished()) {
                qApp->processEvents();
            }

            CProfile * profile = future.result();
            profile->setParent(p);

            return profile;
        }
    }
    return 0;
}

CProfile * CProfileFactory::createInstanceRemote(IProfile *iprofile, const CAuthInfo &authInfo, QThread *thread)
{
    CProfile * profile = iprofile->createInstance(authInfo);
    profile->moveToThread(thread);
    return profile;
}
